<?php

namespace app\cmd;

use app\model\JumpStatPv;
use app\model\JumpStatPvBak;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class StatPvBakCmd extends Command
{
    // php console.php statpv_bak
    protected function configure()
    {
        $this->setName('statpv_bak');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $statModel = new JumpStatPv();
        $table = $statModel->title;
        $model = new \core\lib\Model();
        $statbakmodel = new JumpStatPvBak();
        $tablebak = $statbakmodel->title;
        $bakDate = date('Y-m-d', strtotime("-10 days"));

        // 先检测15天的备份数据是有有了
        $checkID = $statbakmodel->have(['stat_date' => $bakDate], 'id');
        if (!empty($checkID)) {
            echo '已经备份，无需重复备份，$checkID=' . $checkID . ',date=' . $bakDate . PHP_EOL;
            logger('stat')->error('StatPvBak已经备份，无需重复备份，date=' . $bakDate);
            return Command::SUCCESS;
        }

        $total = $statModel->rowsCount(['stat_date' => $bakDate]);
        $pageSize = 1000;
        $step = ceil($total / $pageSize);
        if ($total > 0) {
            $createdAt = date('Y-m-d H:i:s');
            for ($i = 0; $i < $step; $i++) {
                $start = $i > 0 ? ($i * $pageSize) : 0;
                $sql = "insert $tablebak(stat_date,group_no,domain,num_pv,total_pv,rate_pv,created_at,updated_at) select stat_date,group_no,domain,num_pv,total_pv,rate_pv,'{$createdAt}' as created_at,'{$createdAt}' as updated_at from {$table} where stat_date='{$bakDate}' limit $start,$pageSize";
                $rows = $model->query($sql)->rowCount();
                if ($rows > 0) {
                    echo '执行成功' . $rows . '笔：,date=' . $bakDate . ',limit ' . $start . ',' . $pageSize . PHP_EOL;
                }
            }
            // 删除原来的记录
            $statModel->delAll(['stat_date' => $bakDate]);
        } else {
            echo '没有数据可执行' . PHP_EOL;
            logger('stat')->error('StatPvBak没有数据可执行，date=' . $bakDate);
        }

        return Command::SUCCESS;
    }
}